using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PrettyGrilClotheItem : MonoBehaviour
{
    public Animator animator;

    private ScrollRect _scrollRect;

    private RectTransform _rectView;

    private float _startX;

    private float _endX;

    private Vector3 _posRecord;

    private int _aniHash;
    // Start is called before the first frame update
    void Start()
    {
        _rectView = GetComponent<RectTransform>();
        animator = GetComponent<Animator>();
        animator.speed = 0;
        _aniHash = Animator.StringToHash("scroll");
    }

    // Update is called once per frame
    void Update()
    {
        if (transform.position != _posRecord)
        {
            OnPositionChanged();
            _posRecord = transform.position;
        }
    }

    private void OnDestroy()
    {
        // if (_scrollRect)
        // {
        //     _scrollRect.onValueChanged.RemoveListener(OnPositionChanged);   
        // }
    }

    public void Init(ScrollRect scrollRect, RectTransform view)
    {
        if (scrollRect)
        {
            _scrollRect = scrollRect;
            //_scrollRect.onValueChanged.AddListener(OnPositionChanged);   
        }

        if (view)
        {
            //_rectView = view;
            float width = view.sizeDelta.x;
            float centerPosX = view.position.x;   //画布锚点是在正中间的
            _startX = centerPosX - (width / 2);
            _endX = centerPosX +  (width / 2);
            //OnPositionChanged(Vector2.one);
        }
    }
    // 位置变动时，看下当前的位置处在视窗的比例，通过比例调用动画
    public void OnPositionChanged()
    {
        if (!_rectView)
        {
            return;
        }

        float timeScale = (_rectView.position.x - _startX) / (_endX - _startX);
        SetAnimator(timeScale);
    }

    private void SetAnimator(float pos)
    {
        if (pos < 0)
        {
            pos = 0;
        }else if (pos > 1)
        {
            pos = 1;
        }

        if (animator && animator.isActiveAndEnabled)
        {
            animator.Play(_aniHash, -1, pos);
        }
        
    }
    
    
}
